package com.demo.blog;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

import com.demo.common.DemoConfig;
import com.demo.user.User;
import com.jfinal.core.Controller;

import cn.jiahui.HibUtils;

public class JiaJingController  extends Controller{
	
	
	private Test test  = new Test();
	public void index(){
		System.out.println("jiajing.index()");
		renderJson((new User()).set("userName", "test"));
		
		renderJson("{'1':'2'}");
		
	}
	public void socketAck(){
		String result = getPara("result");
		System.out.println("socketAck():" +result);
		
		renderText(result);
	}
	
	public void hartBeat(){
		renderText("heartBeat");
	}
	
	
	
	public void test(){
		 try {
			 
			Socket s=new Socket("127.0.0.1",8088);
			 OutputStream outputStream=s.getOutputStream();  
			 
			 BufferedOutputStream bos = null;
				if (outputStream != null) {
					bos = new BufferedOutputStream(outputStream);
				}
				
				InputStream inputStream = s.getInputStream();
				BufferedInputStream bis = null;
				if(inputStream != null){
					bis = new BufferedInputStream(inputStream);
				}
				if (bos != null) {
					writeCommonForReadBtnState(bos);
				}
				if(bis != null){
					boolean flag = readCommondResult(bis);
					if(flag){
						renderText("{\"state\":\"0\"}");
						return;
					}
				}

		} catch (IOException e) {
			e.printStackTrace();
		}
		 renderText("failed");
	}
 
	//5.2.1.	读取按钮状态
		private void writeCommonForReadBtnState(BufferedOutputStream bos) throws IOException{
			byte data[] = new byte[]
						{
							(byte)0XA1, (byte)0XA2, 
							(byte)0X00, (byte)0X00, 
							(byte)0X00, (byte)0X06, 
							(byte)0X01, (byte)0X01, 
							(byte)0X00, (byte)0X01, 
							(byte)0X00, (byte)0X0A
						};
			bos.write(data);
			bos.flush();
			System.out.println("writeCommonForReadBtnState()");
		}
		private boolean readCommondResult(BufferedInputStream bis) throws IOException{
			int sizeToRead = 11;
			byte data[] = new byte[sizeToRead];
			Arrays.fill(data, (byte)0);
			int beatSize = bis.read(data);
			if(beatSize == sizeToRead){
				System.out.println("button state bytes readed");
				HibUtils.printByte(data);
//				String result = HibUtils.doGet(prefixUrl+"socketAck/?result=ok");
//				System.out.println( result);
				return true;
				
			}else{
				System.out.println("button state bytes readed failed");
//				String result = HibUtils.doGet(prefixUrl+"jiajing/socketAck/?result=failed");
//				System.out.println( result);
				return false;
			}
		}
}

